package com.bottle.web;

import com.alibaba.fastjson.JSON;
import com.bottle.event.ChatRecordEvent;
import com.bottle.event.MessageEvent;
import com.bottle.event.OutInfoEvent;
import com.bottle.event.WSMessageEvent;
import com.bottle.mode.BridgeInfo;
import com.bottle.mode.ReJson;
import com.bottle.mode.RequestMessage;
import com.bottle.mode.UserInfo;
import com.bottle.service.UserService;
import com.bottle.utils.SpringUtil;
import com.google.common.base.Optional;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: chenyuncong
 * @Date: 2020/5/12 16:58
 */
@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }

    private static final AtomicInteger OnlineCount = new AtomicInteger(0);

    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();

//    private static ConcurrentHashMap<String,WebSocketServer> sessionMap = new ConcurrentHashMap<>();

    private static ConcurrentHashMap<String,WebSocketServer> wsSessionMap;


    //用户缓存，
    private static LoadingCache<String, Optional<UserInfo>> loadingCache;

    //桥梁对象 保存用户关系
    private static LoadingCache<String, Optional<BridgeInfo>> bridgeInfoCache;

    //所有用户的加密id
    private static ConcurrentHashMap<String, String> userIdCache;

    private static UserService userService;

    private Session session;

    private String id = "";



    //由于@ServerEndpoint 标记后的bean是多例，spring bean启动注入只会调用一次set方法，把对象引用到静态对象中去即可。
    @Autowired
    public void setWsSessionMape(ConcurrentHashMap<String,WebSocketServer> wsSessionMap) {
        WebSocketServer.wsSessionMap = wsSessionMap;
    }
    @Autowired
    public void setBridgeInfoCache(LoadingCache<String, Optional<BridgeInfo>> bridgeInfoCache){
        WebSocketServer.bridgeInfoCache=bridgeInfoCache;
    }
    @Autowired
    public void setLoadingCache(LoadingCache<String, Optional<UserInfo>> loadingCache){
        WebSocketServer.loadingCache=loadingCache;
    }
    @Autowired
    public void setUserIdCache(ConcurrentHashMap<String, String> userIdCache){
        WebSocketServer.userIdCache=userIdCache;
    }
    @Autowired
    public void setUserService(UserService userService){
        WebSocketServer.userService=userService;
    }

    public Session getSession() {
        return session;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "sid") String sid,Session session) {
        this.session = session;
        this.id = sid;
        log.info("连接id：[{}]",sid);
        wsSessionMap.put(sid,this);
        SpringUtil.publishEvent(new OutInfoEvent(this, sid));
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("有连接加入，当前连接数为：{}", cnt);
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        log.info(this.id);
        wsSessionMap.remove(this.id);
//        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws ExecutionException {
        log.info("来自客户端id:[{}]的消息：{}",session.getId(),message);
        RequestMessage request = null;
        try{
            request = JSON.parseObject(message, RequestMessage.class);
        }catch (Exception e){
            e.printStackTrace();
            log.error("格式错误：[{}]",e.getMessage());
            return;
        }

        //拿到用户加密id，去获取用户对象，拿到用户id
        String userId = userIdCache.get(request.getEncrUserId());
        if (StringUtils.isEmpty(userId)) { //不存在这个用户
            return;
        }
        UserInfo userInfo = loadingCache.get(userId).get(); //用户信息对象，里面用户对应的所有桥梁关系id
        if (StringUtils.isEmpty(userInfo.getUserId())) { //空对象不存在的用户
            return;
        }
        //1、根据桥梁加密id获取到，桥梁对象，拿到桥梁id，获取里面对应得用户信息，
        String encryptionId = request.getEncrBridgeId();
        //检查加密的关系id encryptionId 是否在 自己的集合里面，没有就返回
        if (!userInfo.checkBridgeId(encryptionId)) {
            return;
        }
        BridgeInfo bridgeInfo = bridgeInfoCache.get(encryptionId).get(); //获取桥梁对象
        if (!bridgeInfo.checkUserId(request.getEncrUserId())) { //用户不在关系里面，
            return;
        }
        if (StringUtils.isEmpty(bridgeInfo.getUserIds())) {//不存在的用户关系
            return;
        }

        Set<String> onLineSet = userService.userOnLineSet(request.getEncrUserId(),bridgeInfo,wsSessionMap.keySet());

        SpringUtil.publishEvent(new ChatRecordEvent(this,request.getContent(),System.currentTimeMillis(),request.getSendTime(),userId,encryptionId));

//        SpringUtil.publishEvent(new WSMessageEvent(this, request.getContent(), onLineSet));

        for(String euId: onLineSet){
            if(wsSessionMap.containsKey(euId)){
                WebSocketServer ws = wsSessionMap.get(euId);
                if(ws==null){
                    return;
                }
                Session seesionClient=ws.session;
                if(seesionClient!=null){
                    synchronized (seesionClient){
                        if(seesionClient.isOpen()){
                            SendMessage(ws.session, "收到消息，消息内容："+request.getContent());
                        }
                    }

                }
            }
        }

    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : SessionSet) {
            if(session.isOpen()){
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message,String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }

}
